﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Security.Principal;


namespace PreContractWeb
{
    public class Global : System.Web.HttpApplication
    {
        protected void Session_Start(Object sender, EventArgs e)
        {

        }

        protected void Session_End(Object sender, EventArgs e)
        {
            
        }

        private static bool _maintainStatus;
        public static bool MaintainStatus
        {
            get
            {
                return _maintainStatus;

            }
            set
            {
                _maintainStatus = value;
            }
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            // 初始化数据维护状态
            MaintainStatus = false;

            BEGDC.PreContract.BLL.IMenuConfig menulist = (BEGDC.PreContract.BLL.IMenuConfig)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_MenuConfig_Service];

            EmailScheduler.Start();


            string constr = "cZqKOSZUEQcxklKx3gZurajG7wFZtjiiTq3am9SppfepxAAtoC74hy8UZwHvkTnZ5f1JHPCrcaYvO/MfRB4F3EJyXiPk0U3EMayTxjpkHdw=";
            string a = BEGDC.Utility.Security.EncryptTool.Decrypt(constr, BEGDC.Utility.Configuration.ConfigConst.Key);

            constr = "cZqKOSZUEQcxklKx3gZurajG7wFZtjiiTq3am9SppfepxAAtoC74hy8UZwHvkTnZR/bzsoSRHKhxT9XW2ZC/mBzcgW9/W8FUQF/mRDp9eqPKrvRB1NcAVA==";
            string b = BEGDC.Utility.Security.EncryptTool.Decrypt(constr, BEGDC.Utility.Configuration.ConfigConst.Key);
        }

        protected void Application_End(object sender, EventArgs e)
        {
            EmailScheduler.Stop();
        }

        private void FormAuthentication(string username)
        {

            //create form authentication ticket.
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                2,         // Ticket version
                username,  // Username associated with ticket
                //true,    //isPersistent
                DateTime.Now,// Date/time issued
                DateTime.Now.AddHours(1),//time to expire
                false,       // "true" for a persistent user cookie
                "",          // User-data, in this case the roles
                FormsAuthentication.FormsCookiePath);// Path cookie valid for

            // Encrypt the cookie using the machine key for secure transport
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));

            // Set the cookie's expiration time to the tickets expiration time
            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;


            // Add the cookie to the list for outgoing response
            Response.Cookies.Add(cookie);

            // Create an Identity.
            GenericIdentity id = new GenericIdentity(ticket.Name, "PreContractWebAuthentication");

            // This principal flows throughout the request.
            GenericPrincipal principal = new GenericPrincipal(id, (string[])null);

            //string name = principal.Identity.Name;

            BEGDC.PreContract.BLL.Authentication.PCPrincipal princi = BEGDC.PreContract.BLL.Authentication.PCPrincipal.GetPrincipal(principal);

            princi.Reload();

            BaseFunction.CreateLog(BEGDC.PreContract.BLL.OperationLog.OperationType.Login, "Login", username);

            //if (Request.Cookies["RedirectURL"] != null)
            //{
            //    if (Request.Cookies["RedirectURL"].Value != null)

            //        Response.Redirect(HttpContext.Current.Request.Cookies["RedirectURL"].Value.ToString());
            //}
            //string url = System.Web.Security.FormsAuthentication.GetRedirectUrl(username, false);

            //if (url == string.Empty)
            //{
            //    Response.Redirect("~/Default.aspx");
            //}
            //else
            //{

            //    Response.Redirect(System.Web.Security.FormsAuthentication.GetRedirectUrl(username, false));
            //}

        }

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User is System.Security.Principal.WindowsPrincipal)  //window auth
                    {
                        FormAuthentication(HttpContext.Current.User.Identity.Name);
                    }

                    HttpContext.Current.User = BEGDC.PreContract.BLL.Authentication.PCPrincipal.GetPrincipal(HttpContext.Current.User);

                    if (HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User;
                    }
                    else
                    {
                        HttpContext.Current.Response.Redirect("~/AccessDenied.htm", true);
                    }
                }
            }
        }
    }
}